//***定义为全局变量***
//获取驱动信息
var driver = JSON.parse($("#dirverJson").text());
//显示驱动数据源和目标源
function showDriverEditInfo(driver) {
	var sourceMapping = driver.sourceMapping;
	var targetMapping = driver.mappings[0];
	
	var sourceConn = DriverConnectorConstant[sourceMapping.connector];
	var targetConn = DriverConnectorConstant[targetMapping.connector];
	// 获取数据源和目标源连接器图标
	var sourceIcon = sourceConn['icon'];
	$("#sourceIcon").attr("class", "fa " + sourceIcon + ' fa-4x');
	var targetIcon = targetConn['icon'];
	$("#targetIcon").attr("class", "fa " + targetIcon + ' fa-4x');

	// 获取数据源和目标源连接器类型
	var sourceType = sourceConn['type'];
	$("#sourceType").text("类型：" + sourceType);
	var targetType = targetConn['type'];
	$("#targetType").text("类型：" + sourceType);
	
	// 如果驱动被禁用
	if(!driver.enable){
		$(".driverEnable").attr("disabled","disabled");
	}
}

//显示驱动编辑配置（迁移/同步）
function showDriverEditConfig(opr){
	var url = '';
	switch (opr) {
	case 'migration':
		url = $basePath+"/driver/page/driverEditMigration";
		break;
	case 'sync':
		url = $basePath+"/driver/page/driverEditSync";
		break;
	default:
		break;
	}
	if(url != ''){
		$.post(url,function(resp){
			// 加载后端响应视图
			$("#driverEditConfigContainer").html(resp);
		});
	}
}

//绑定修改驱动同步方式切换事件
function bindEventForDriverEditConfig($driverEditConfigChange, driver) {
	// 初始化icheck插件
	$driverEditConfigChange.find("input").iCheck({
		labelHover : false,
		cursor : true,
		radioClass : 'iradio_flat-blue',
	}).on('ifChecked', function(event){
		showDriverEditConfig($(this).val());
	});
	
	var model = 'all'==driver.model ? 0 : 1;
	// 默认渲染数据迁移配置
	$driverEditConfigChange.find("input").eq(model).iCheck("check");
}

//获取基本信息
function saveDriverConfigProperty(driver) {
	var trs = $("#propertyList").find("tr");
	var sourceFileds = [];
	var targetFileds = [];
	trs.each(function(i, o) {
		var sField = $(this).find("td:eq(0)");
		var tField = $(this).find("td:eq(1)");
		sourceFileds.push({
			"name" : sField.text(),
			"type" : sField.attr("type"),
			"typeName" : sField.attr("typeName")
		});
		targetFileds.push({
			"name" : tField.text(),
			"type" : tField.attr("type"),
			"typeName" : tField.attr("typeName")
		});
	});
	driver.sourceMapping.fileds = sourceFileds;
	driver.mappings[0].fileds = targetFileds;
}

//获取迁移配置
function saveDriverConfigMigration(driver) {
	//设置为迁移
	driver.model = "all";
	saveDriverConfigProperty(driver);
	
	//过滤条件
	var ands = [];
	var ors = [];
	var trs = $("#conditionList").find("tr");
	trs.each(function(i, o) {
		var combination = $(this).find("td:eq(0)").attr('name');
		var name = $(this).find("td:eq(1)").attr('name');
		var operator = $(this).find("td:eq(2)").attr('name');
		var value = $(this).find("td:eq(3)").attr('name');
		if ("and" == combination) {
			ands.push({
				"name" : name,
				"operator" : operator,
				"value" : value
			});
		} else if ("or" == combination) {
			ors.push({
				"name" : name,
				"operator" : operator,
				"value" : value
			});
		}
	});
	driver.query = {};
	driver.query.and = ands;
	driver.query.or = ors;
}

//获取同步配置
function saveDriverConfigSync(driver) {
	saveDriverConfigProperty(driver);
	//设置为同步
	driver.model = "increment";
	driver.policy = {};
	// 判断时候数据库连接器类型
	var sourceMapping = driver.sourceMapping;
	if(sourceMapping.connector==ConnectorConstantDatabase){
		driver.policy.increment = {};
		var enable = $("#driverStrategyIncrementEnable").find("input[type='checkbox']").val();
		var driverClassName = sourceMapping.config.driverClassName;
		if(driverClassName=='com.mysql.jdbc.Driver'){
			var ip = $("#sourceStrategyIncrementIp").val();
			var port = parseInt($("#sourceStrategyIncrementPort").val());
			var instance = $("#sourceStrategyIncrementInstance").val();
			var database = $("#sourceStrategyIncrementDatabase").val();
			var table = $("#sourceStrategyIncrementTable").val();
			driver.policy.increment = {
				"enable" : enable,
				"type":"mysql",
				"ip" : ip,
				"port" : port,
				"instance" : instance,
				"database" : database,
				"table" : table
			};
			return;
		}
		if(driverClassName=='oracle.jdbc.OracleDriver'){
			var scanAll = $("#sourceStrategyIncrementScanAll").find('[name="scanAll"]:checked').val();
			var dictionary = $("#sourceStrategyIncrementDictionaryPath").val();
			driver.policy.increment = {
				"enable" : enable,
				"type":"oracle",
				"scanAll" : scanAll,
				"dictionary" : dictionary
			};
			return;
		}
	}
}

//保存驱动配置
function saveDriverConfig(id, driver) {
	// migration sync
	id = id.find("input[name='driverEditConfig']:checked").val();
	switch (id) {
	case 'migration':
		// 数据迁移
		saveDriverConfigMigration(driver);
		// 回显同步属性作为条件
		initConditionColumn($("#conditionSourceField"), driver.sourceMapping.fileds);
		break;
	case 'sync':
		// 数据同步
		saveDriverConfigSync(driver);
		break;
	default:
		break;
	}
	// 保存驱动配置
	$.post($basePath + "/driver/update", {
		"mapping" : JSON.stringify(driver)
	}, function(data) {
		if (data.success == true) {
			bootGrowl(data.resultValue, "success");
			$initContainer.load($basePath + "/index");
		} else {
			bootGrowl(data.resultValue, "danger");
		}
	});
}

$(function() {
	// 显示驱动编辑信息
	showDriverEditInfo(driver);
	// 加载数据迁移
	var $driverEditConfigChange = $('#driverEditConfigChange');
	bindEventForDriverEditConfig($driverEditConfigChange, driver);
	
	// 保存
	$("#driverSubBtn").click(function() {
		saveDriverConfig($driverEditConfigChange, driver);
	});
	// 返回
	$("#driverBackIndexBtn").click(function() {
		// 加载页面
		$initContainer.load($basePath + "/index");
	});
})